import * as http from "http";
import * as fs from "fs";

function getFileCB(url: string, targetPath: string, cb: (e?: Error) => void) {
    http.get(url, (res) => {
        //HTTP状态码
        const {statusCode} = res;
        if (statusCode !== 200) {
            let error = new Error('Request Failed.\n' + `Status Code: ${statusCode}`);
            console.error(`getFile HttpConnection error: ${error.message}`);
            res.resume();
            cb(error);
            return;
        }

        //文件写入流
        let ws = fs.createWriteStream(targetPath);
        ws.on('error', (e) => {
            console.error(`getFile WriteStream error: ${e.message}`);
            cb(e);
        });

        //返回流
        res.pipe(ws);
        res.on('error', (e) => {
            console.error(`getFile ResponseStream error: ${e.message}`);
            cb(e)
        });

        //正常结束
        res.on('end', () => {
            cb();
        });

    }).on('error', (e) => {
        //异常中断
        console.error(`getFile HttpConnection error: ${e.message}`);
        cb(e);
    });
}


async function getFileAsync(url: string, targetPath: string): Promise<Error | void> {
    return new Promise((resolve, reject) => {
            getFileCB(url, targetPath, (e) => {
                if (e) reject(e);
                else resolve();
            })
        }
    )
}

export {getFileCB, getFileAsync}